import React, { useState, useContext, createContext } from 'react';

// 创建上下文空间
const NumContext = createContext();
console.log('NumContext:', NumContext);

function Son(){
    // const { num } = useContext(NumContext);
    // return <div>啦啦啦{num}</div>
    return (
        // useContext 消费者
        <NumContext.Consumer>
            {/* 内部可以接收到context的数据，通过解构使用 */}
            {
                ({num}) => <div>呵呵呵{num}</div>
            }
        </NumContext.Consumer>
    )
}

function Btn(){
    return (
        <NumContext.Consumer>
            {
                ({num,setNum}) => <button onClick={ () => { setNum(num + 1) }} >累加</button>
            }
        </NumContext.Consumer>
    )
}

export default function UseContextTest(){
    const [num,setNum] = useState(0);

    return (
        <div>
            {/* 
              *上下文空间提供器 
              单参传递，value={变量}
              多参处传递，value={ obj }  传递对象
            */}
            <NumContext.Provider value={{ num,setNum }}>
                <Son />
                <Btn />
            </NumContext.Provider>
        </div>
    )
}